// JavaScript Document
$(document).ready(function(){
	
	$('.delete').click(function (cl) {
		var link_attr = $(this).attr('href');
		$.prompt("Deleting this item will permanently remove it from the system", {
			title: "Are you sure?",
			buttons: { "Delete": true, "Cancel": false },
			submit: function(e,v,m,f){
			if(v) window.location.href = link_attr;
		}
		});
		
		return false;
	});
	
	$('.reset').click(function (cl) {
		var link_attr = $(this).attr('href');
		$.prompt("This will reset the user's password, a new password will be sent to user's email address", {
			title: "Are you sure?",
			buttons: { "Reset": true, "Cancel": false },
			submit: function(e,v,m,f){
			if(v) window.location.href = link_attr;
		}
		});
		
		return false;
	});
	
	if($('#s_chat_box').is(':visible')){

		var last_id = 0;
		var chat_id_string = '';
		get_chats();
		setInterval(get_latest_chat, 5000); //
		
		function get_latest_chat(){
			var b_id = $('#booking_id').val();
			
			 $.ajax({
                    url: "ajax/get_latest_chat/", 
                    type: "POST",
                    dataType: "json",
                    async: true,
   				    data: "booking_id=" + b_id + "&chat_id_string=" + chat_id_string, 
					success: function(data) {
						if(data){
							$.each(data, function(i, item) {
							
							// console.log('My ID: '+$('#my_id').val()+' || Last: '+last_id+ ' || '+($('#my_id').val() == last_id) + ' || Message: '+item.message)
							
							 
   						    if(last_id == item.chat_by){
								//console.log('entered');
								if(!$('#s_chat_box').find('.cbox').is(':visible')){
									
									if($('#my_id').val() == last_id)
										$('#s_chat_box').append(assemble_chat(item.message, 'you'));
									else
										$('#s_chat_box').append(assemble_chat(item.message, 'them'));	
								}
								else {								
									console.log('last appended');
									$('#s_chat_box .cbox').last().append('<p>'+item.message+'</p>');
								}
							}
							else {
								//console.log('Un Matched');
								if($('#my_id').val() == item.chat_by) {
									
									$('#s_chat_box').append(assemble_chat(item.message, 'you'));
								}
								else
									$('#s_chat_box').append(assemble_chat(item.message, 'them'));
							}
							
							chat_id_string = chat_id_string+item.id+',';
							last_id = item.chat_by;
							//console.log(last_id);
							console.log(chat_id_string);
 						 });
						}
					},
					error: function(e) {
                    	console.log(e);
                    }
			 });
			
		}
		
		$('#s_send').click(function (){
			if($('#s_msg').val() == '')
				alert('Please place a message');
			else {
				var msg = $('#s_msg').val();
				var booking_id = $('#booking_id').val();
				var chat_by = $('#my_id').val();
				insert_chat(msg, booking_id, chat_by);
							
					
				$('#s_msg').val('');
			}
			return false;
		})
		
		$('#s_msg').keypress(function(event){
			var keycode = (event.keyCode ? event.keyCode : event.which);
			if(keycode == '13'){
				if($('#s_msg').val() == '')
				alert('Please place a message');
				else {
					var msg = $('#s_msg').val();
					var booking_id = $('#booking_id').val();
					var chat_by = $('#my_id').val();
					insert_chat(msg, booking_id, chat_by);
								
						
					$('#s_msg').val('');
				}
				return false;
			}
			event.stopPropagation();
		});
		
		function insert_chat(msg, b_id, chatby_id){
			var my_id = $('#my_id').val();
	 		$.ajax({
                    url: "ajax/chat/", 
                    type: "POST",
                    dataType: "json",
                    async: true,
   				    data: "message=" + msg +"&booking_id="+b_id+"&chat_by="+chatby_id, 
					success: function(data) {
					
						
						if($('#s_chat_box .cbox').last().hasClass('you'))
							$('#s_chat_box .cbox').last().append('<p>'+data.msg+'</p>');
						else
							$('#s_chat_box').append(assemble_chat(data.msg, 'you'));
						
						last_id = data.chat_by;
						chat_id_string = chat_id_string+data.last_chat_id+',';
					},
					error: function(e) {
                    	console.log(e);
                    }
			 });
	
		}
		
		function get_chats(){
			var b_id = $('#booking_id').val();
			
			 $.ajax({
                    url: "ajax/get_chat/", 
                    type: "POST",
                    dataType: "json",
                    async: true,
   				    data: "booking_id=" + b_id, 
					success: function(data) {
						console.log(data);
						 $.each(data, function(i, item) {
							
							// console.log('My ID: '+$('#my_id').val()+' || Last: '+last_id+ ' || '+($('#my_id').val() == last_id) + ' || Message: '+item.message)
														 
   						    if(last_id == item.chat_by){
								//console.log('entered');
								if(!$('#s_chat_box').find('.cbox').is(':visible')){
									
									if($('#my_id').val() == last_id)
										$('#s_chat_box').append(assemble_chat(item.message, 'you'));
									else
										$('#s_chat_box').append(assemble_chat(item.message, 'them'));	
								}
								else {								
									console.log('last appended');
									$('#s_chat_box .cbox').last().append('<p>'+item.message+'</p>');
								}
							}
							else {
								//console.log('Un Matched');
								if($('#my_id').val() == item.chat_by) {
									
									$('#s_chat_box').append(assemble_chat(item.message, 'you'));
								}
								else
									$('#s_chat_box').append(assemble_chat(item.message, 'them'));
							}
							
							chat_id_string = chat_id_string+item.id+',';
							last_id = item.chat_by;
							//console.log(last_id);
							console.log(chat_id_string);
 						 });
					},
					error: function(e) {
                    	console.log(e);
                    }
			 });
			
		}
		
		
	} /* end if($('#chatbox').is(':visible'))*/
	
	
	//Set default open/close settings
	$('.acc_container').hide(); //Hide/close all containers
	$('.acc_trigger.active').next().show(); 
	
	//On Click
	$('.acc_trigger').click(function(){
		if( $(this).next().is(':hidden') ) { //If immediate next container is closed...
			$('.acc_trigger').removeClass('active').next().slideUp(); //Remove all .acc_trigger classes and slide up the immediate next container
			$(this).toggleClass('active').next().slideDown(); //Add .acc_trigger class to clicked trigger and slide down the immediate next container
		}
		return false; //Prevent the browser jump to the link anchor
	});
	
	$('#tbl-list').dataTable({
		"sPaginationType": "full_numbers",
		"bJQueryUI": true,
	});
	
	
	$('#tbl-list-time').dataTable({
		"sPaginationType": "full_numbers",
		"bJQueryUI": true,
		"aoColumns": [
                { "bSortable": false },
               { "sType": 'string-case' },
                { "bSortable": false }
            ],
		"aaSorting": []
	});
	
	$('#booking-list').dataTable({
		"sPaginationType": "full_numbers",
		"bJQueryUI": true,
		"aoColumns": [
                null,
				null,
				null,
				null,
				{ "sType": 'string-case' },
				null,
				{ "bSortable": false }
            ],
		"aaSorting": []
	});
	
});

	/* Define two custom functions (asc and desc) for string sorting */
	jQuery.fn.dataTableExt.oSort['time-range-asc']  = function(x,y) {
	  
	  var d1 = new Date();
	  
	  var time = x.match(/(\d+)(?::(\d\d))?\s*(P?)/);
	  console.log('Time: '+time)
	  d1.setHours( parseInt(time[1]) + (time[3] ? 12 : 0) );
	  if(!time[3] && parseInt(time[1])==12) d1.setHours(0);
	  d1.setMinutes( parseInt(time[2]) || 0 );
	  
	  var d2 = new Date();
	  time = y.match(/(\d+)(?::(\d\d))?\s*(P?)/);
	  d2.setHours( parseInt(time[1]) + (time[3] ? 12 : 0) );
	  if(!time[3] && parseInt(time[1])==12) d2.setHours(0);
	  d2.setMinutes( parseInt(time[2]) || 0 );
	  
	  console.log(x+' => '+d1.getTime());
	  console.log(y+' => '+d2.getTime());
				  
	  x = d1.getTime();
	  y = d2.getTime();
	  
	  return ((x < y) ? -1 : ((x > y) ?  1 : 0));
	  
	};

	/* Define two custom functions (asc and desc) for string sorting */
	jQuery.fn.dataTableExt.oSort['string-case-asc']  = function(x,y) {
	  
	  var d1 = new Date();
	  
	  var time = x.match(/(\d+)(?::(\d\d))?\s*(P?)/);
	  console.log('Time: '+time)
	  d1.setHours( parseInt(time[1]) + (time[3] ? 12 : 0) );
	  if(!time[3] && parseInt(time[1])==12) d1.setHours(0);
	  d1.setMinutes( parseInt(time[2]) || 0 );
	  
	  var d2 = new Date();
	  time = y.match(/(\d+)(?::(\d\d))?\s*(P?)/);
	  d2.setHours( parseInt(time[1]) + (time[3] ? 12 : 0) );
	  if(!time[3] && parseInt(time[1])==12) d2.setHours(0);
	  d2.setMinutes( parseInt(time[2]) || 0 );
	  
	  console.log(x+' => '+d1.getTime());
	  console.log(y+' => '+d2.getTime());
				  
	  x = d1.getTime();
	  y = d2.getTime();
	  
	  return ((x < y) ? -1 : ((x > y) ?  1 : 0));
	  
	};
	
	jQuery.fn.dataTableExt.oSort['string-case-desc'] = function(x,y) {
	
	  var d1 = new Date();
	  var time = x.match(/(\d+)(?::(\d\d))?\s*(P?)/);
	  d1.setHours( parseInt(time[1]) + (time[3] ? 12 : 0) );
	  if(!time[3] && parseInt(time[1])==12) d1.setHours(0); 
	  d1.setMinutes( parseInt(time[2]) || 0 );
	  
	  var d2 = new Date();
	  time = y.match(/(\d+)(?::(\d\d))?\s*(P?)/);
	  d2.setHours( parseInt(time[1]) + (time[3] ? 12 : 0) );
	  if(!time[3] && parseInt(time[1])==12) d2.setHours(0);
	  d2.setMinutes( parseInt(time[2]) || 0 );
	  
	  x = d1.getTime();
	  y = d2.getTime();
	  
		return ((x < y) ?  1 : ((x > y) ? -1 : 0));
	};
	
function assemble_chat(msg, type){
	var chat_class = type == 'you' ? 'you' : 'them';
	var text = type == 'you' ? 'You' : $('#client_name').val()+' (Client) ';
	var chat = '<div class="'+chat_class+' cbox"><span>'+text+'</span><p>'+msg+'</p></div>';
	return chat;
}